package com.saunter.utils;

import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

public class FileUtils {
    public static String getClassPath() throws IOException {
        return ResourceUtils.getURL("classpath:").getPath();
    }

    public static String getProjectPath() {
        try {
            return new File(getClassPath()).getParentFile().getParent();
        }catch (Exception e) {
            return "";
        }
    }

    public static String saveFile(MultipartFile file, String full_path) throws IOException {
        FileInputStream fileInputStream = (FileInputStream) file.getInputStream();
        File goal_file = new File(full_path);
        File goal_dir = goal_file.getParentFile();
        if(!goal_dir.exists()){
            if(!goal_dir.mkdirs()) {
                return "create dir fail";
            }
        }
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(goal_file));
        byte[] bs = new byte[1024];
        int len;
        while ((len = fileInputStream.read(bs)) != -1) {
            bos.write(bs, 0, len);
        }
        bos.flush();
        bos.close();
        return "1";
    }
}
